<template>
    <el-dialog v-model="visible" :title="title" :width="width" @closed="resetForm" @open="init" :close-on-press-escape="false">
        <el-form ref="formRef" :model="obj" :rules="rules" label-width="100px" label-position="left" label-suffix="：">
            <el-form-item label="编号" prop="id" style="display: none">
                <el-input v-model="obj.id"/>
            </el-form-item>
            <el-form-item label="上级菜单" prop="parentId">
                <el-cascader
                    v-model="obj.parentId"
                    :options="this.$store.state.menuOptions.length===0?[]:this.$store.state.menuOptions[0].children"
                    :props="menuCascade.props"
                    placeholder="选择上级菜单"
                    :show-all-levels="false"
                    clearable
                    :filterable="true"
                />
            </el-form-item>
            <el-form-item label="菜单类型" prop="type">
                <el-radio-group v-model="obj.type">
                    <el-radio :label="0">目录</el-radio>
                    <el-radio :label="1">菜单</el-radio>
                    <el-radio :label="2">按钮</el-radio>
                </el-radio-group>
            </el-form-item>
<!--            <el-form-item label="域名" prop="url">-->
<!--                <el-input placeholder="请输入域名" clearable v-model="obj.url"/>-->
<!--            </el-form-item>-->
            <el-form-item label="路由地址" prop="path">
                <el-input placeholder="请输入路由地址" clearable v-model="obj.path" ref="path"/>
            </el-form-item>
            <el-form-item label="菜单名称" prop="menuName">
                <el-input placeholder="请输入菜单名称" class="a" v-model="obj.menuName"/>
            </el-form-item>
            <el-form-item label="路由组件" prop="component">
                <el-input placeholder="请输入路由组件" v-model="obj.component"/>
            </el-form-item>
            <el-form-item label="菜单图标" prop="iconId">
                <template v-if="obj.iconUrl!=null">
                    <img :src="`/${obj.iconUrl}`" alt="" style="width: 18px;position: relative;top: 0;">
                </template>
                <template v-else>
                    无
                </template>
                <el-tooltip content="删除图标" placement="top">
                    <el-button :icon="Delete" @click="deleteIcon" style="margin-left:10px" v-show="obj.iconId!==null"></el-button>
                </el-tooltip>
                <el-tooltip content="选择图标" placement="top">
                    <el-button :icon="Search" @click="selectIcon" style="margin-left:10px"></el-button>
                </el-tooltip>
                <div class="icon-options" v-if="menuIcons">
                    <menu-icons-box @select-item="saveSelectIcon" @hidden-box="menuIcons=false"/>
                </div>
            </el-form-item>
            <el-form-item label="显示顺序" prop="sort">
                <el-input-number :min="1" controls-position="right" v-model="obj.sort"/>
            </el-form-item>
            <el-form-item label="权限认证" prop="requireAuth">
                <el-checkbox v-model="obj.requireAuth" :true-label="1" :false-label="0"/>
            </el-form-item>
            <el-form-item label="显示状态" prop="keepAlive" class="half-item">
                <el-radio-group v-model="obj.keepAlive">
                    <el-radio :label="1">显示</el-radio>
                    <el-radio :label="0">隐藏</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="菜单状态" prop="enabled" class="half-item">
                <el-radio-group v-model="obj.enabled">
                    <el-radio :label="1">正常</el-radio>
                    <el-radio :label="0">停用</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <template v-if="type === 0">
                <el-button type="primary" @click="submitAdd">确认添加</el-button>
            </template>
            <template v-if="type === 1">
                <el-button type="primary" @click="submitUpdate">确认修改</el-button>
            </template>
            <el-button type="default" @click="visible = false">取消</el-button>
        </template>
    </el-dialog>
</template>

<script>
    import {ElMessage} from "element-plus";
    import {Search,Delete} from '@element-plus/icons-vue';
    import {addMenu, updateMenu, hasSameMenuPath, hasSameNameSiblingMenu} from "../../../../network/sys/menu";
    import MenuIconsBox from "../../../../components/MenuIconsBox.vue";
    import {getCurrentInstance, reactive, ref, toRefs} from "vue";

    export default {
        name: "MenuForm",
        components: {MenuIconsBox},
        props:{
            width: ''
        },
        setup(props,{emit}) {
            const globalProperties = getCurrentInstance()?.appContext.config.globalProperties;//全局属性
            const visible = ref(false);
            const formRef = ref(null);
            const validateMenuPath = (rule, value, callback)=>{
                hasSameMenuPath({
                    id: form.obj.id,
                    path: value
                }).then(vo => {
                    if (vo) {
                        callback(new Error('已存在相同的菜单路径'));
                    }
                    callback();
                })
            }
            const validateMenuName = (rule,value,callback)=>{
                hasSameNameSiblingMenu({
                    id: form.obj.id,
                    menuName: form.obj.menuName,
                    parentId: form.obj.parentId ? form.obj.parentId : 0
                }).then(vo=>{
                    if(vo){
                        callback(new Error('该目录下已有相同名称的菜单！'))
                    }
                    callback();
                })
            }
            const form = {
                obj: reactive({
                    id: null,
                    parentId: 0,
                    type: 0,
                    url: null,
                    path: null,
                    menuName: null,
                    component: null,
                    iconId: null,
                    iconUrl: null,
                    requireAuth: 1,
                    sort: 1,
                    keepAlive: 1,
                    enabled: 1
                }),
                rules : reactive({
                    menuName: [
                        {required: true,message: '请输入菜单名称',trigger: 'blur'},
                        {validator: validateMenuName,trigger: 'blur'},
                    ],
                    path:[
                        {required: true,message: '请输入菜单路由地址',trigger: 'blur'},
                        {validator: validateMenuPath,trigger: 'blur'},
                    ]
                }),
                setObj({id, parentId, type, url, path, menuName, component, iconId, iconUrl, requireAuth, sort, keepAlive, enabled}){
                    form.obj.id = id;
                    form.obj.parentId = parentId;
                    form.obj.type = type;
                    form.obj.url = url;
                    form.obj.path = path;
                    form.obj.menuName = menuName;
                    form.obj.component = component;
                    form.obj.iconId = iconId;
                    form.obj.iconUrl = iconUrl;
                    form.obj.requireAuth = requireAuth;
                    form.obj.sort = sort;
                    form.obj.keepAlive = keepAlive;
                    form.obj.enabled = enabled;
                },
                resetForm(){
                    formRef.value.resetFields();
                    formRef.value.clearValidate();
                },
                submitAdd(){
                    formRef.value.validate((valid)=>{
                        if(valid){
                            addMenu(form.obj).then(vo=>{
                                globalProperties.$response.handle({
                                    data: vo,
                                    success: '添加菜单成功',
                                    error: vo.msg,
                                    successFn: ()=>{
                                        emit('refresh-data');//刷新数据表格
                                        visible.value = false;
                                    }
                                })
                            })
                        }else{
                            ElMessage.error('请先填写正确的表单数据')
                        }
                    })
                },
                submitUpdate(){
                    formRef.value.validate((valid)=>{
                        if(valid){
                            updateMenu(form.obj).then(vo=>{
                                globalProperties.$response.handle({
                                    data: vo,
                                    success: '修改成功',
                                    error: vo.msg,
                                    successFn: ()=>{
                                        emit('refresh-data');
                                        visible.value = false;
                                    }
                                })
                            })
                        }else{
                            ElMessage.error('请先填写正确的表单数据')
                        }
                    })
                }
            }//表单属性
            return{
                ...toRefs(form),
                formRef,
                visible,
                Search,Delete
            }
        },
        emits:['refresh-data'],
        data(){
            return{
                menuIcons: false,
                menuCascade:{
                    // options: [],
                    props:{
                        label: 'label',
                        value: 'value',
                        children: 'children',
                        emitPath: false,
                        checkStrictly: true
                    }
                },
                title: null,
                type: null,
            }
        },
        methods:{
            deleteIcon(){
                this.obj.iconId = null;
                this.obj.iconUrl = null;
            },
            focusPath(){
                this.$refs.path.focus();
            },
            saveSelectIcon(item){
                this.menuIcons = false;
                this.obj.iconId = item.id;
                this.obj.iconUrl = item.url;
                // console.log('当前选中的图标：',item)
            },
            selectIcon(){
                this.menuIcons = !this.menuIcons;
            },
            init(){
                // console.log('this.state.menuOptions',this.$store.state.menuOptions);
            }
        },
        created() {
        }
    }
</script>

<style scoped>
    *{
        /*border: 1px solid red;*/
    }
    .el-select-dropdown__item{
        width: 100%;
    }
    .icon-options{
        position: absolute;
        top: 140%;
        z-index: 99;
    }
    .half-item{
        width: 43%;
        float: left;
    }
</style>
<style>
    .el-cascader-node{
        width: 100%;
    }
    .el-scrollbar__view{
        width: 180px;
    }
</style>
